/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anism.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.anism.API.HolidayInputLocal;
import org.anism.entity.Employee;

/**
 *
 * @author tgqm5519
 */
@WebServlet(name = "InputHolidayRequestServlet", urlPatterns = {"/InputHolidayRequestServlet"})
public class InputHolidayRequestServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        boolean isAuthenticated = false;
        boolean hasFailedLogin = false;
        Employee emp = null;
        HolidayInputLocal holidayInput = null;

        // Lookup HolidayInput session bean
        try {
            Context jndiContext = new InitialContext();
            holidayInput = (HolidayInputLocal) jndiContext.lookup("java:global/Holidays2-war/HolidayInput!org.anism.API.HolidayInputLocal");
        } catch (NamingException ex) {
            Logger.getLogger(InputHolidayRequestServlet.class.getName()).log(Level.SEVERE, "Unable to lookup session bean", ex);
        }

        // Check if user is logged in
        if (request.getSession(true).getAttribute("user.authenticated") != null) {
            isAuthenticated = true;
        } else {
            String login = request.getParameter("login");
            String password = request.getParameter("password");

            // Check if user has completed the  authentication form
            if (login != null && password != null) {
                emp = holidayInput.authenticate(login, password);

                if (emp != null) {
                    request.getSession().setAttribute("user.authenticated", true);
                    request.getSession().setAttribute("user.firstname", emp.getFirstName());
                    request.getSession().setAttribute("user.lastname", emp.getLastName());
                    request.getSession().setAttribute("user.id", emp.getEmployeeId());
                    isAuthenticated = true;
                } else {
                    hasFailedLogin = true;
                }
            }
        }

        if (!isAuthenticated) { // user is not logged in, display authentication form
            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Authentication</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Authentication</h1>");

                if (hasFailedLogin) {
                    out.println("<p>Authentication failed, please try again</p>");
                }
                out.println("<form action=\"./InputHolidayRequestServlet\" method=\"post\" >");
                out.println("Login : <input type=\"text\" name=\"login\"/><br />");
                out.println("Password : <input type=\"text\" name=\"password\" /><br />");
                out.println("<input type=\"submit\" value=\"Submit\" />");
                out.println("</form>");
                out.println("<p><a href=\"index.jsp\" >Go back to menu</a></p>");
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
            }
        } else { // user is authenticated
            Date today = GregorianCalendar.getInstance().getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

            String employeeId = (String) request.getSession().getAttribute("user.id");
            String startDateString = request.getParameter("start_date");
            String endDateString = request.getParameter("end_date");
            String holidayType = request.getParameter("holiday_type");

            if (employeeId != null && startDateString != null && endDateString != null && holidayType != null) {
                try {
                    holidayInput.addHolidayRequest(
                            employeeId,
                            sdf.parse(startDateString),
                            sdf.parse(endDateString),
                            holidayType);
                } catch (ParseException ex) {
                    Logger.getLogger(InputHolidayRequestServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Input a holiday request</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<p>You are logged in as "
                        + request.getSession().getAttribute("user.id")
                        + " - <a href=\"signout.jsp\" >sign out</a>"
                        + "</p>");
                out.println("<h1>Input a holiday request</h1>");
                out.println("<p>Firstname : " + request.getSession().getAttribute("user.firstname") + "<br />");
                out.println("Lastname : " + request.getSession().getAttribute("user.lastname") + "</p>");
                out.println("<form action=\"./InputHolidayRequestServlet\" method=\"post\" >");
                out.println("Holiday Type : <select name=\"holiday_type\" size=\"1\" >");
                out.println("<option selected=\"true\">annual leave</option>");
                out.println("<option>other leave</option>");
                out.println("</select><br />");
                out.println("Start date : <input type=\"text\" name=\"start_date\" value=\""
                        + sdf.format(today)
                        + "\"/><br />");
                out.println("End date : <input type=\"text\" name=\"end_date\" value=\""
                        + sdf.format(today)
                        + "\"/><br />");
                out.println("<input type=\"submit\" value=\"Submit\" />");
                out.println("");
                out.println("</form>");
                out.println("<p><a href=\"index.jsp\" >Go back to menu</a></p>");
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
